package com.cloudm.technician.ui.service

import android.app.IntentService
import android.content.Context
import android.content.Intent
import com.cloudm.technician.extensions.baseApplication
import com.cloudm.technician.extensions.logger_e
import com.cloudm.technician.ui.base.BaseApplication
import com.cloudm.technician.ui.widget.AppBlockCanaryContext
import com.github.moduth.blockcanary.BlockCanary
import com.squareup.leakcanary.LeakCanary

/**
 * 作者: wesley
 * 时间: 2017/11/21
 * 描述: service
 */
class InstallTreasureIntentService(name: String = "InstallTreasureIntentService") : IntentService(name) {

    companion object {
        const val ACTION_INTENT_SERVICE = "com.cloudm.api.technician.service"
        fun start(context: Context) {
            val intent = Intent(context, InstallTreasureIntentService::class.java).apply {
                action = ACTION_INTENT_SERVICE
            }
            context.startService(intent)
        }
    }

    override fun onHandleIntent(intent: Intent?) {
        val action = intent?.action
        if (action != null && action == ACTION_INTENT_SERVICE) {
            initCanary()
        }
    }


    private fun initCanary() {
        baseApplication?.let {
            initLeakCanary(it)
            initBlockCanary(it)
        }
    }


    private fun initLeakCanary(application: BaseApplication) {

        when (LeakCanary.isInAnalyzerProcess(application)) {
            false -> {
                LeakCanary.install(application)
            }

            else -> {
                logger_e(" initLeakCanary isInAnalyzerProcess is true")
            }
        }
    }

    private fun initBlockCanary(application: BaseApplication) {
        BlockCanary.install(application, AppBlockCanaryContext())
    }
}